package com.spmsys.util;

import org.jetbrains.annotations.NotNull;

import java.io.*;

/**
 * 文件工具类
 */
public class FileUtil {

    /**
     * 通过类加载器读取文件
     *
     * @param clazz 类
     * @param path  路径
     * @return 数据
     */
    public static @NotNull String readFileByClassLoader(Class<?> clazz, String path) {
        try (InputStream inputStream = clazz.getClassLoader().getResourceAsStream(path)) {
            if (inputStream == null) {
                throw new RuntimeException("文件" + path + "读取失败");
            }
            try (InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
                String line;
                StringBuilder stringBuilder = new StringBuilder();
                //读取文件
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                //返回数据
                return stringBuilder.toString();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 读取文件方法
     *
     * @param path 文件路径
     * @return 文件数据
     */
    public static @NotNull String readFile(String path) {
        File file = new File(path);
        //如果文件不存在则抛出异常
        if (!file.exists()) {
            throw new RuntimeException("文件" + path + "不存在");
        }
        try (FileReader fileReader = new FileReader(path); BufferedReader bufferedReader = new BufferedReader(fileReader)) {
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            //读取文件
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            //返回数据
            return stringBuilder.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 写入文件方法
     *
     * @param path   文件路径
     * @param data   数据
     * @param append 是否追加
     */
    public void writeFile(String path, String data, Boolean append) {
        File file = new File(path);
        try {
            //如果文件不存在则创建文件，创建失败则抛出异常
            if (!file.exists() && !file.createNewFile()) {
                throw new RuntimeException(path + "文件创建失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try (FileWriter fileWriter = new FileWriter(file.getAbsoluteFile(), append); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
            //写入文件
            bufferedWriter.write(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
